package com.ifnk.portaljava.dapWeb.dataPacket;
/**
 * <p>Title: 类型转换类</p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2010</p>
 *
 * <p>Company: </p>
 *
 * @author WenSheng.Song.hlyt@gmail.com
 * @version 1.0
 */
public class TransformFunction {
	public static byte[] charToByteArray(char c) {
		byte[] charBuf = new byte[2];
		for (int i = 0; i < 2; i++) {
			int offset = (charBuf.length - 1 - i) * 8;
			charBuf[i] = (byte) ((c >>> offset) & 0xff);
		}
		return charBuf;
	}

	public static final int byteArrayToChar(byte[] b) {
		return (b[0] << 8) + (b[1] & 0xFF);
	}

	public static byte[] shortToByteArray(short s) {
		byte[] shortBuf = new byte[2];
		for (int i = 0; i < 2; i++) {
			int offset = (shortBuf.length - 1 - i) * 8;
			shortBuf[i] = (byte) ((s >>> offset) & 0xff);
		}
		return shortBuf;
	}

	public static final int byteArrayToShort(byte[] b) {
		return (b[0] << 8) + (b[1] & 0xFF);
	}

	public static byte[] intToByteArray(int value) {
		byte[] b = new byte[4];
		for (int i = 0; i < 4; i++) {
			int offset = (b.length - 1 - i) * 8;
			b[i] = (byte) ((value >>> offset) & 0xFF);
		}
		return b;
	}

	public static final int byteArrayToInt(byte[] b) {
		return (b[0] << 24) + ((b[1] & 0xFF) << 16) + ((b[2] & 0xFF) << 8)
				+ (b[3] & 0xFF);
	}

	public static byte[] longToByteArray(long value) {
		byte[] b = new byte[8];

		for (int i = 0; i < 8; i++) {
			int offset = (b.length - 1 - i) * 8;
			b[i] = (byte) ((value >>> offset) & 0xFF);
		}

		return b;
	}

	public static final int byteArrayToLong(byte[] b) {
		return (b[0] << 56) + ((b[1] & 0xFF) << 48) + ((b[2] & 0xFF) << 40)
				+ ((b[3] & 0xFF) << 32) + ((b[4] & 0xFF) << 24)
				+ ((b[5] & 0xFF) << 16) + ((b[6] & 0xFF) << 8)
				+ ((b[7] & 0xFF) << 0);
	}

	public static final int byteArrayToShort(byte[] b, int start) {
		return (b[start] << 8) + (b[start + 1] & 0xFF);
	}

	public static final int byteArrayToInt(byte[] b, int start) {
		return (b[start] << 24) + ((b[start + 1] & 0xFF) << 16)
				+ ((b[start + 2] & 0xFF) << 8) + (b[start + 3] & 0xFF);
	}
}
